package com.oo.app.ui.main.activity;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.oo.app.R;
import com.oo.app.base.activities.BaseActivity;
import com.oo.app.ui.dialog.LoginSelectSexDialog;
import com.oo.app.ui.main.activity.boy.HomeBoyActivity;
import com.oo.app.ui.main.activity.girl.GrabChatActivity;
import com.oo.app.widget.CustomDatePicker;
import com.oo.app.widget.toast.Prompt;
import com.oo.app.widget.toast.SnackbarToast;
import com.yuyh.library.imgsel.ISNav;
import com.yuyh.library.imgsel.common.ImageLoader;
import com.yuyh.library.imgsel.config.ISCameraConfig;
import com.yuyh.library.imgsel.config.ISListConfig;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import butterknife.BindView;
import butterknife.OnClick;
import de.hdodenhof.circleimageview.CircleImageView;

/**
 * @创建者 喻亚龙
 * @描述 完善资料
 */

public class UserInfoCompileActivity extends BaseActivity implements View.OnClickListener{

    private static final int REQUEST_LIST_CODE = 0;

    private static final int REQUEST_CAMERA_CODE = 1;
    //请求访问外部存储
    public static final int READ_EXTERNAL_STORAGE_REQUEST_CODE = 103;
    //请求写入外部存储
    public static final int WRITE_EXTERNAL_STORAGE_REQUEST_CODE = 104;

    @BindView(R.id.iv_portrait)
    CircleImageView ivPortrait;

    @BindView(R.id.tv_username)
    TextView tvUserName;

    @BindView(R.id.tv_year)
    TextView tvYear;

    @BindView(R.id.iv_sex_female)
    ImageView ivSexFemale;

    @BindView(R.id.iv_sex_male)
    ImageView ivSexMale;

    @BindView(R.id.tv_sex_male)
    TextView tvSexMale;

    @BindView(R.id.tv_sex_female)
    TextView tvSexFemale;

    @BindView(R.id.et_invitation_code)
    EditText etInvitationCode;

    @BindView(R.id.btn_login)
    Button btnLogin;

    private CustomDatePicker customDatePicker;

    private boolean isLogin = false;

    private String sexStr = "";


    public static void show(Context context) {
        Intent intent = new Intent(context, UserInfoCompileActivity.class);
        context.startActivity(intent);
    }

    @Override
    protected int getContentView() {
        return R.layout.activity_userinfo_compile;
    }


    @Override
    protected void initWidget() {
        super.initWidget();

        initDatePicker();


    }

    @Override
    protected void initData() {
        super.initData();

        ISNav.getInstance().init(new ImageLoader() {
            @Override
            public void displayImage(Context context, String path, ImageView imageView) {
                Glide.with(context).load(path).into(imageView);
            }
        });

    }

    @OnClick({R.id.iv_back,R.id.btn_login,R.id.iv_sex_male,R.id.iv_sex_female,R.id.tv_year,R.id.iv_portrait})
    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.iv_back:
                finish();
                break;
            case R.id.btn_login:
                if (isLogin){
                    loginNoChange();
                }
                break;
            case R.id.iv_sex_male:
                sexStr = "男";
                ivSexFemale.setImageResource(R.mipmap.login_icon_female_default);
                ivSexMale.setImageResource(R.mipmap.login_icon_male_selected);
                tvSexFemale.setTextColor(getResources().getColor(R.color.textColor_9));
                tvSexMale.setTextColor(getResources().getColor(R.color.login_male_text));
                btnLogin.setBackgroundResource(R.mipmap.login_btn_selected);
                isLogin = true;
                break;
            case R.id.iv_sex_female:
                sexStr = "女";
                ivSexFemale.setImageResource(R.mipmap.login_icon_female_selected);
                ivSexMale.setImageResource(R.mipmap.login_icon_male_default);
                tvSexFemale.setTextColor(getResources().getColor(R.color.login_female_text));
                tvSexMale.setTextColor(getResources().getColor(R.color.textColor_9));
                btnLogin.setBackgroundResource(R.mipmap.login_btn_selected);
                isLogin = true;

                break;
            case R.id.tv_year:
                // 日期格式为yyyy
                customDatePicker.show(tvYear.getText().toString());

                break;
            case R.id.iv_portrait:
                uploadHeadImage();

                break;
        }
    }

    private void initDatePicker() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy", Locale.CHINA);
        String now = sdf.format(new Date());
        tvYear.setText(now);

        customDatePicker = new CustomDatePicker(this, new CustomDatePicker.ResultHandler() {
            @Override
            public void handle(String time) { // 回调接口，获得选中的时间
                tvYear.setText(time.split(" ")[0]);
            }
        }, "1950", now); // 初始化日期格式请用：yyyy，否则不能正常运行
        customDatePicker.showSpecificTime(true); // 不显示时和分
        customDatePicker.setIsLoop(true); // 不允许循环滚动
    }

    /**
     * 上传头像
     */
    public void uploadHeadImage() {
        View view = LayoutInflater.from(this).inflate(R.layout.upload_head_popupwindow, null);
        TextView btnCarema = (TextView) view.findViewById(R.id.btn_camera);
        TextView btnPhoto = (TextView) view.findViewById(R.id.btn_photo);
        TextView btnCancel = (TextView) view.findViewById(R.id.btn_cancel);
        final PopupWindow popupWindow = new PopupWindow(view, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        popupWindow.setBackgroundDrawable(getResources().getDrawable(android.R.color.transparent));
        popupWindow.setOutsideTouchable(true);
        View parent = LayoutInflater.from(this).inflate(R.layout.activity_main, null);
        popupWindow.showAtLocation(parent, Gravity.BOTTOM, 0, 0);
        //popupWindow在弹窗的时候背景半透明
        final WindowManager.LayoutParams params = getWindow().getAttributes();
        params.alpha = 0.5f;
        getWindow().setAttributes(params);
        popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                params.alpha = 1.0f;
                getWindow().setAttributes(params);
            }
        });



        btnCarema.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //权限判断
                if (ContextCompat.checkSelfPermission(UserInfoCompileActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                        != PackageManager.PERMISSION_GRANTED) {
                    //申请WRITE_EXTERNAL_STORAGE权限
                    ActivityCompat.requestPermissions(UserInfoCompileActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                            WRITE_EXTERNAL_STORAGE_REQUEST_CODE);
                } else {
                    //跳转到调用系统相机
                    Camera();
                }
                popupWindow.dismiss();
            }
        });
        btnPhoto.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //权限判断
                if (ContextCompat.checkSelfPermission(UserInfoCompileActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE)
                        != PackageManager.PERMISSION_GRANTED) {
                    //申请READ_EXTERNAL_STORAGE权限
                    ActivityCompat.requestPermissions(UserInfoCompileActivity.this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
                            READ_EXTERNAL_STORAGE_REQUEST_CODE);
                } else {
                    //跳转到调用系统图库
                    Single();
                }
                popupWindow.dismiss();
            }
        });
        btnCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow.dismiss();
            }
        });

    }

    public void Single() {
        ISListConfig config = new ISListConfig.Builder()
                // 是否多选
                .multiSelect(false)
                .btnText("Confirm")
                // 确定按钮背景色
                .btnBgColor(Color.parseColor("#FFFFFF"))
                // 确定按钮文字颜色
                .btnTextColor(getResources().getColor(R.color.black))
                // 使用沉浸式状态栏
                .statusBarColor(getResources().getColor(R.color.theme_color))
                // 返回图标ResId
                .backResId(R.mipmap.nav_icon_return_black)
                .title("相机照片")
                .titleColor(getResources().getColor(R.color.black))
                .titleBgColor(getResources().getColor(R.color.white))
                .allImagesText("All Images")
                .needCrop(true)
                .cropSize(1, 1, 200, 200)
                // 第一个是否显示相机
                .needCamera(false)
                // 最大选择图片数量
                .maxNum(9)
                .build();

        ISNav.getInstance().toListActivity(this, config, REQUEST_LIST_CODE);
    }

    public void Camera() {
        ISCameraConfig config = new ISCameraConfig.Builder()
                .needCrop(true)
                .cropSize(1, 1, 200, 200)
                .build();

        ISNav.getInstance().toCameraActivity(this, config, REQUEST_CAMERA_CODE);
    }



    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_LIST_CODE && resultCode == RESULT_OK && data != null) {
            List<String> pathList = data.getStringArrayListExtra("result");

            // 测试Fresco
            // draweeView.setImageURI(Uri.parse("file://"+pathList.get(0)));
            for (String path : pathList) {
//                tvResult.append(path + "\n");
            }
        } else if (requestCode == REQUEST_CAMERA_CODE && resultCode == RESULT_OK && data != null) {
            String path = data.getStringExtra("result");
//            tvResult.append(path + "\n");
        }
    }

    /**
     * 提交后 性别提交后无法修改
     */
    public void loginNoChange(){
        final LoginSelectSexDialog loginSelectSexDialog = new LoginSelectSexDialog(UserInfoCompileActivity.this);
        loginSelectSexDialog.show();
        loginSelectSexDialog.setClicklistener(new LoginSelectSexDialog.ClickListenerInterface() {
            @Override
            public void doConfirm() {
                if (sexStr.equals("男")){
                    HomeBoyActivity.show(UserInfoCompileActivity.this);
                }else if (sexStr.equals("女")){
                    GrabChatActivity.show(UserInfoCompileActivity.this);
                }
                loginSelectSexDialog.dismiss();
            }

            @Override
            public void doCancel() {
                loginSelectSexDialog.dismiss();
            }
        });
    }
}
